import { getAllModules, queryModule, addModule, editModule, delModule } from '@/services/module';

export default {
  namespace: 'module',

  state: {
    data: {
      list: [],
      pagination: {},
    },
  },

  effects: {
    *getAllModules({ payload }, { call, put }) {
      const resp = yield call(getAllModules, payload);
      const { data = [] } = resp;
      yield put({
        type: 'saveAllModules',
        payload: data,
      });
    },
    *fetchByParams({ payload }, { call, put }) {
      const resp = yield call(queryModule, payload);
      yield put({
        type: 'savePage',
        payload: resp.data,
      });
    },
    *add({ payload, callback }, { call }) {
      const response = yield call(addModule, payload);
      if (response && response.state === 0) {
        if (callback) callback();
      }
    },
    *update({ payload, callback }, { call }) {
      const response = yield call(editModule, payload);
      if (response && response.state === 0) {
        if (callback) callback();
      }
    },
    *remove({ payload, callback }, { call }) {
      const response = yield call(delModule, payload);
      if (response && response.state === 0) {
        if (callback) callback();
      }
    },
  },

  reducers: {
    saveAllModules(state, action) {
      return {
        ...state,
        allModules: action.payload,
      };
    },
    savePage(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
  },
};
